package com.xx.xiawan.net;

import android.content.Context;
import android.util.Log;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.Volley;

/**
 * Created by Administrator on 2017-09-01.
 */

public abstract class DGRequestBase<T> implements Response.Listener<T> ,Response.ErrorListener  {
    protected Request<T> mRequest;
    protected RequestQueue mRequestQueue;
    protected T mResponse;
    protected Object lock = new Object();
    protected Context mContext;
    protected DGJsonResult jsonResult;
    protected DGRequestListener mRequestListener;
    protected boolean isLock = true;
    public DGRequestBase(Context context,DGRequestListener listener){
        mContext = context;
        mRequestListener = listener;
        jsonResult = new DGJsonResult();
    }
    public DGJsonResult start(){
      //  mRequestQueue = Volley.newRequestQueue(mContext);
       // mRequestQueue.add(mRequest);
        DGHttpClient.defaultClient(mContext).doRequest(mRequest);
        isLock = true;
        synchronized (lock){
            try {
                lock.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return jsonResult;
    }

    public void startNoLock(){
      //  mRequestQueue = Volley.newRequestQueue(mContext);
      //  mRequestQueue.add(mRequest);
        DGHttpClient.defaultClient(mContext).doRequest(mRequest);
        isLock = false;

    }
    public void onResponse(T response){
        mResponse = response;
        jsonResult.result = mResponse.toString();
        unLock();
    }

    protected void unLock(){
        if(isLock){
            synchronized (lock){
                lock.notify();
            }
        }
    }

    public void onErrorResponse(VolleyError error){
        mResponse = null;
        jsonResult.errorCode = DGJsonResult.REQUEST_ERROR;
        if(mRequestListener != null){
            mRequestListener.onError(error.toString());
        }
        unLock();
    }

    public void header(String name, String value) {

    }

    public static void quit(Context context){
        DGHttpClient.exit(context);
    }
}